import React, { useState } from "react";
import { LockOutlined, UserOutlined } from "@ant-design/icons";
import { Button, Form, Input, Flex, Typography } from "antd";
import "./index.css";
import { validateUsername, validatePassword } from "./validate";
import { useNavigate } from "react-router-dom";

const { Title } = Typography;

export const LoginComponent = (props) => {
  const navigate = useNavigate();
  // 表单校验
  const [form] = Form.useForm();
  const [submittable, setSubmittable] = useState(false); // 表单是否可提交
  const onValuesChange = (_, allValues) => {
    const allFieldsFilled = Object.values(allValues).every((value) => {
      if (typeof value === "string") {
        return value.trim() !== "";
      }
      return Boolean(value);
    });
    setSubmittable(allFieldsFilled);
  };
  // 提交表单
  const onFinish = (values) => {
    const user = JSON.parse(localStorage.getItem("user"));
    if (
      user.username === values.username &&
      user.password === values.password
    ) {
      navigate("/home");
    } else {
      message.error("用户名或密码错误");
    }
  };

  return (
    <div className="login_container">
      <Form
        form={form}
        name="login"
        autoComplete="false"
        validateTrigger="onSubmit"
        className="login-form"
        onFinish={onFinish}
        onValuesChange={onValuesChange}
      >
        <Title level={2} className="login-title">
          登录
        </Title>
        <Form.Item
          name="username"
          validateTrigger="onSubmit"
          rules={[
            {
              validator: validateUsername,
            },
          ]}
        >
          <Input prefix={<UserOutlined />} placeholder="用户名" />
        </Form.Item>
        <Form.Item
          name="password"
          validateTrigger="onSubmit"
          rules={[
            {
              validator: validatePassword,
            },
          ]}
        >
          <Input.Password
            prefix={<LockOutlined />}
            type="password"
            placeholder="密码"
          />
        </Form.Item>
        <Form.Item>
          <Button
            block
            className="login-button"
            type={submittable ? "primary" : "default"}
            htmlType="submit"
            disabled={!submittable}
          >
            登录
          </Button>
        </Form.Item>
        <Form.Item>
          <Flex justify="space-between" align="center">
            <a onClick={props.handleForgotPassword}>忘记密码</a>
            <div style={{ textAlign: "center" }}>
              没有账号?
              <a onClick={props.handleRegister}>快速注册</a>
            </div>
          </Flex>
        </Form.Item>
      </Form>
    </div>
  );
};
